package MD5Cookies;
#
# Make MD5 "signatures"
#
use strict;
use vars qw($num $key $verifier);

use MD5;
use Carp;

sub tsign {
    my ($num, $key, $timeout) = @_;

    my $tstamp = time() + $timeout;
    return sign("$num/$tstamp", $key);
}

sub tverify {
    my ($verifier, $key) = @_;
    if ($verifier =~ /[^\/]+\/(\d+)/) {
	if (time() > $1) {
	    return 0;
	} else {
	    return verify($verifier, $key);
	}
    } else {
	warn "Illegal format of verifier\n";
        return 0;
    }
}

sub sign {
    my ($num, $key) = @_;
    my $salt = int(rand() * 1000); # bad source of randomness
    return sign_salted($num, $salt, $key);
}

sub sign_salted {
    my ($num, $salt, $key) = @_;
    my $tosign = "$num:A:$salt:$key:$salt";
    my $sig = MD5->hexhash($tosign);
    my $verifier = "$num:A:$salt:";
    $verifier .= substr($sig, 0, 10);
    $verifier;
}

sub verify {
    my ($verifier, $key) = @_;
    my ($num, $method, $salt, $sig) = split(":", $verifier);
    if ($method ne "A") { 
        warn "Unsupported method: $method\n";
        return 0;
    } else {
        my $expected = sign_salted($num, $salt, $key);
        return ($expected eq $verifier);
    }
}
    
1;
